<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Userdetail;

class UserdetailsController extends Controller {
    public function details(){
        return view('Home\userdetails');
    }
    public function postdetails(request $req){
        $path = "upload/user/".$req->user()->name ;
        if (!is_dir($path)) {
            mkdir($path , 0777 , true);
        }
        $data = $req->input();
        $data['img'] = url($this->makeThumb($_FILES['img']['tmp_name'] , $path));
        $data['imghg'] = url("images/hg.png");
        $data['uid'] = $req->user()->uid;
        return Userdetail::updateOrCreate(['uid'=>$data['uid']] , $data) ? redirect('details') : 'error';
    }
    protected function makeThumb($ori , $path , $sw=64 , $sh=64) {
        $path = $path."/".$_FILES['img']['name'];
        $opic = $ori; //大图的绝对路径
        $opath = $path;//小图的绝对路径
        if(!list($bw,$bh,$type) = getimagesize($opic)) {
        return false;
        }
        $map = array(
        1=>'imagecreatefromgif',
        2=>'imagecreatefromjpeg',
        3=>'imagecreatefrompng',
        6=>'imagecreatefromwbmp',
        15=>'imagecreatefromwbmp'
        );
        //如果传来的图片类型不再map里 无法处理 则return false
        if( !isset($map[$type]) ) {
        return false;
        } 
        $func = $map[$type];
        $big = $func($opic);
        //创建小画布
        $small = imagecreatetruecolor($sw, $sh);
        $white = imagecolorallocate($small, 255, 255, 255);
        imagefill($small, 0, 0, $white);
        //计算缩略比
        $rate = min( $sw/$bw , $sh/$bh );
        /*imagecopyresampled ( $small , $big , int $dst_x , int $dst_y , 0 , 0 , int $dst_w , int $dst_h , $bw , $bh )*/
        //真正粘到小图上的宽高
        $rw = $bw*$rate;
        $rh = $bh*$rate;
        imagecopyresampled ( $small , $big , ($sw-$rw)/2 , ($sh-$rh)/2 , 0 , 0 , $rw , $rh , $bw , $bh );
        //保存缩略图
        imagepng($small , $opath);
        //销毁画布
        imagedestroy($big);
        imagedestroy($small);
        return $path;
    }
}
